extends Area2D

var screen_size
signal died

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	screen_size = get_viewport_rect().size
	hide()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	var d = direction_according_to_input()

	flip(d)
	move(d, delta)
	animate(d)

func _on_body_entered(_body: Node2D) -> void:
	$CollisionShape2D.set_deferred("disabled", true)
	hide()
	died.emit()

func show_at(pos):
	$CollisionShape2D.disabled = false
	position = pos
	show()

func direction_according_to_input() -> Vector2:
	var d = Vector2.ZERO
	
	if Input.is_action_pressed("ui_left"):
		d.x -= 1
	if Input.is_action_pressed("ui_right"):
		d.x += 1
	if Input.is_action_pressed("ui_up"):
		d.y -= 1
	if Input.is_action_pressed("ui_down"):
		d.y += 1

	return d.normalized()

func flip(d):
	$AnimatedSprite2D.flip_h = when_moving_left(d)
	$AnimatedSprite2D.flip_v = when_moving_down(d)

func move(d, t):
	position += t*d*400
	position = position.clamp(Vector2.ZERO, screen_size)

func animate(d):
	if is_stationary(d):
		$AnimatedSprite2D.stop()
		return
	
	if has_vertical_move(d):
		$AnimatedSprite2D.animation = "swim"
	else:
		$AnimatedSprite2D.animation = "walk"

	$AnimatedSprite2D.play()

func when_moving_left(d) -> bool:
	return d.x < 0

func when_moving_down(d) -> bool:
	return d.y > 0

func is_stationary(d) -> bool:
	return d.length() <= 0

func has_vertical_move(d) -> bool:
	return d.y != 0
